//
//  GWBarAnimationView.m
//  Glowalker
//
//  Created by Harvey on 2017/10/9.
//  Copyright © 2017年 Haley. All rights reserved.
//

#import "GWBarAnimationView.h"

static const CGFloat subLayerW = 10;//子图层的宽
static const CGFloat subLayerH = 0.1;//子图层的高
static const CGFloat subLayerMargin = 2;//子图层的间隙
#define subLayerC DefaultColor //子图层的背景色
#define repLayerC [UIColor clearColor] //复制图层的颜色

@interface GWBarAnimationView ()

@property (nonatomic,strong) CALayer *subLayer;
@property (nonatomic,strong) CAReplicatorLayer *repLayer;//复制图层

@end

@implementation GWBarAnimationView

- (CAReplicatorLayer *)repLayer
{
    if (!_repLayer) {
        CAReplicatorLayer *repLayer = [CAReplicatorLayer layer];
        repLayer.frame = self.bounds;
        repLayer.backgroundColor = repLayerC.CGColor;
        CALayer *subLayer = [CALayer layer];
        subLayer.backgroundColor = subLayerC.CGColor;
        subLayer.anchorPoint = CGPointMake(0, 1);
        subLayer.frame = CGRectMake(0,0, subLayerW, subLayerH);
        subLayer.position = CGPointMake(subLayerMargin, CGRectGetMaxY(repLayer.frame) / 2  + 20);
        subLayer.cornerRadius = 2;
        subLayer.masksToBounds = YES;
        [repLayer addSublayer:subLayer];
        [self.layer addSublayer:repLayer];
        _subLayer = subLayer;
        _repLayer = repLayer;
    }
    return _repLayer;
}

- (void)drawRect:(CGRect)rect {
    self.repLayer.instanceCount = (self.repLayer.frame.size.width - 2 * subLayerMargin) / (self.subLayer.frame.size.width + subLayerMargin);
    self.repLayer.instanceTransform = CATransform3DMakeTranslation(subLayerW + subLayerMargin, 0, 0);
    self.repLayer.instanceDelay = 0.2; //动画延迟时间
    //添加动画
    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"transform.scale.y"];
    animation.toValue = @(arc4random_uniform(_scale));
    animation.duration = 0.2;
    animation.repeatCount = MAXFLOAT;
    animation.autoreverses = YES;//动画反转
    [self.subLayer addAnimation:animation forKey:nil];
}

- (void)setScale:(CGFloat)scale
{
    _scale = scale + 20;
    [self setNeedsDisplay];
}

@end
